package com.quanyan.signup.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.signup.constants.Const;
import com.quanyan.signup.entity.db.TbExpertUser;
import com.quanyan.signup.entity.db.TbExpertUserExample;
import com.quanyan.signup.entity.db.TbReferUser;
import com.quanyan.signup.entity.db.TbReferUserExample;
import com.quanyan.signup.entity.vo.req.ReqSerchReferUser;
import com.quanyan.signup.entity.vo.resp.RespMyReferUser;
import com.quanyan.signup.entity.vo.resp.RespSearchExpert;
import com.quanyan.signup.mapper.MyDefineMapper;
import com.quanyan.signup.mapper.TbExpertUserMapper;
import com.quanyan.signup.mapper.TbReferUserMapper;
import com.quanyan.signup.service.SignUpAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/7/7.
 */
@Service("signUpAdminServiceImpl")
public class SignUpAdminServiceImpl implements SignUpAdminService {

    @Autowired
    private TbExpertUserMapper tbExpertUserMapper;

    @Autowired
    private TbReferUserMapper tbReferUserMapper;

    @Autowired
    private MyDefineMapper myDefineMapper;

    /**
     * 达人管理界面访问及条件查询
     * @param reqSerchReferUser
     * @return
     */
    @Override
    public APIResponse<PageObj<List<TbExpertUser>>> getExpertUserMsg(ReqSerchReferUser reqSerchReferUser) {
        Map<String,Object> paramMap=reqSerchReferUser.getParamMap();
        TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
        expertMsg(paramMap,tbExpertUserExample);
        //查询总数
        int totalCount=tbExpertUserMapper.countByExample(tbExpertUserExample);
        tbExpertUserExample.setOrderByClause("id desc");
        Page page=new Page(reqSerchReferUser.getPageNum(),reqSerchReferUser.getPageSize(),totalCount);
        tbExpertUserExample.setPage(page);
        List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
        PageObj<List<TbExpertUser>> result=PageObj.create(totalCount,reqSerchReferUser.getPageNum(),reqSerchReferUser.getPageSize(),tbExpertUserList);
        return APIResponse.returnSuccess(result);
    }

    /**
     * url="" 全部，0=未上传，1=已上传
     * 达人管理查询结果导出
     * @param reqSerchReferUser
     * @return
     */
    @Override
    public APIResponse<List<TbExpertUser>> exportExpertUserMsg(ReqSerchReferUser reqSerchReferUser) {
        Map<String,Object> paramMap=reqSerchReferUser.getParamMap();
        TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
        expertMsg(paramMap,tbExpertUserExample);
        List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
        return APIResponse.returnSuccess(tbExpertUserList);
    }

    private void expertMsg(Map<String,Object> paramMap,TbExpertUserExample tbExpertUserExample){
        if (paramMap!=null){
            TbExpertUserExample.Criteria criteria=tbExpertUserExample.createCriteria();
            String begin= (String) paramMap.get("signTimeBegin");
            String end= (String) paramMap.get("signTimeEnd");
            if(!StringUtil.isBlankOrNull(begin) && !StringUtil.isBlankOrNull(end)){
                begin=begin+" 00:00:00";
                end=end+" 23:59:59";
                criteria.andSignTimeBetween(DateUtils.strToDate(begin,DateUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS),DateUtils.strToDate(end,DateUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS));
            }
            Object oid=paramMap.get("id");
            if (oid!=null && !"".equals(oid)){
                int id=Integer.parseInt((String) oid);
                criteria.andIdEqualTo(id);
            }
            Object omobile=paramMap.get("mobile");
            if (omobile!=null && !"".equals(omobile)){
                criteria.andMobileEqualTo((String)omobile);
            }
            Object osport=paramMap.get("sport");
            if(osport!=null && !"".equals(osport)){
                int sport=Integer.parseInt((String) osport);
                criteria.andSportEqualTo(sport);
            }
            Object oexp_choice=paramMap.get("exp_choice");
            if(oexp_choice!=null && !"".equals(oexp_choice)){
                int exp_choice=Integer.parseInt((String) oexp_choice);
                if (exp_choice==2){//达人类型未知
                    criteria.andExpChoiceIsNull();
                }else{
                    criteria.andExpChoiceEqualTo(exp_choice);
                }

            }
            Object oname=paramMap.get("name");
            if(oname!=null && !"".equals(oname)){
                criteria.andNameLike("%"+oname+"%");
            }
            Object ogender=paramMap.get("gender");
            if(ogender!=null && !"".equals(ogender)){
                int gender=Integer.parseInt((String) ogender);
                criteria.andGenderEqualTo(gender);
            }
            Object ocity=paramMap.get("city");
            if(ocity!=null && !"".equals(ocity)){
                int city=Integer.parseInt((String) ocity);
                criteria.andCityEqualTo(city);
            }
            Object odistrict=paramMap.get("district");
            if(odistrict!=null&&!"".equals(odistrict)){
                int district=Integer.parseInt((String) odistrict);
                criteria.andDistrictEqualTo(district);
            }
            Object osignStatu=paramMap.get("signStatus");
            if(osignStatu!=null && !"".equals(osignStatu)){
                int signStatu=Integer.parseInt((String) osignStatu);
                criteria.andSignStatuEqualTo(signStatu);
            }
            Object ophotoUrl=paramMap.get("photoUrl");
            if (ophotoUrl!=null && !"".equals(ophotoUrl)){
                String url= (String) ophotoUrl;
                if ("0".equals(url)){//未上传
                    criteria.andPhotoUrlIsNull();
                }else {//已上传
                    criteria.andPhotoUrlIsNotNull();
                }
            }
        }
    }

    /**
     * 修改达人状态
     * @param map
     * @return
     */
    @Override
    @Transactional
    public APIResponse setSignStatu(Map<String,Object> map) {
        if(map!=null){
            String mobile= (String) map.get("mobile");
            if(!StringUtil.isBlankOrNull(mobile)){
                TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
                tbExpertUserExample.createCriteria().andMobileEqualTo(mobile);
                TbExpertUser tbExpertUser=tbExpertUserMapper.selectByExample(tbExpertUserExample).get(0);
                if(tbExpertUser.getSignStatu()==Const.SIGN_EXPERT){
                    return APIResponse.returnFail("该用户已签约，不可重复提交");
                }
                String status= (String) map.get("status");
                int statu=Integer.parseInt(status);
                if(statu== Const.SIGN_EXPERT){//已签约 6
                    String referMobile=tbExpertUser.getRefermobile();
                    if(!StringUtil.isBlankOrNull(referMobile)){//推荐人号码存在，跟新推荐用户信息表
                        TbReferUserExample tbReferUserExample=new TbReferUserExample();
                        tbReferUserExample.createCriteria().andMobileEqualTo(referMobile);
                        TbReferUser tbReferUser=tbReferUserMapper.selectByExample(tbReferUserExample).get(0);
                        if(tbExpertUser.getExpert()==Const.PRETTY){//颜值 0
                            tbReferUser.setPrettyNum((short) (tbReferUser.getPrettyNum()+1));
                            tbReferUser.setAllMoney(tbReferUser.getAllMoney()+Const.PRETTY_MONEY);
                        }else {//实力
                            tbReferUser.setExpertNum((short) (tbReferUser.getExpertNum()+1));
                            tbReferUser.setAllMoney(tbReferUser.getAllMoney()+Const.EXPERT_MONEY);
                        }
                        tbReferUserMapper.updateByExampleSelective(tbReferUser,tbReferUserExample);
                    }
                }
                tbExpertUser.setSignStatu((byte)statu);
                tbExpertUserMapper.updateByExampleSelective(tbExpertUser,tbExpertUserExample);//跟新达人状态
                return APIResponse.returnSuccess("状态跟新成功");
            }
        }
        return APIResponse.returnFail("参数不能为空");
    }


    /**
     * 删除达人
     * @param mobile
     * @return
     */
    @Override
    @Transactional
    public APIResponse delExpertUser(String mobile) {
        if(!StringUtil.isBlankOrNull(mobile)){
            TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
            tbExpertUserExample.createCriteria().andMobileEqualTo(mobile);
            List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
            if(tbExpertUserList.size()>0){
                TbExpertUser tbExpertUser=tbExpertUserList.get(0);
                int statu=tbExpertUser.getSignStatu();
                if(statu==Const.GET_INTERVIE || statu==Const.SIGN_EXPERT){//4,6
                    return APIResponse.returnFail(80,"该达人已签约或已通过面试，不能删除");
                }
                tbExpertUserMapper.deleteByExample(tbExpertUserExample);//删除达人
                //跟新推荐人--推荐的达人数量
                TbReferUserExample tbReferUserExample=new TbReferUserExample();
                tbReferUserExample.createCriteria().andMobileEqualTo(tbExpertUser.getRefermobile());
                List<TbReferUser> tbReferUserList=tbReferUserMapper.selectByExample(tbReferUserExample);
                if (tbReferUserList.size()>0){
                    TbReferUser tbReferUser=tbReferUserList.get(0);
                    tbReferUser.setAllNum(tbReferUser.getAllNum()-1);
                    tbReferUserMapper.updateByExampleSelective(tbReferUser,tbReferUserExample);
                }
                return APIResponse.returnSuccess("删除达人成功");
            }else{
                return APIResponse.returnFail(90,"该达人不存在，删除达人失败");
            }
        }
        return APIResponse.returnFail(70,"手机号不能为空，删除达人失败");
    }

    /**
     * 面试录入结果
     * @param map
     * @return
     */
    @Override
    public APIResponse insertInterviewResult(Map<String, Object> map) {
        if (map!=null){
            String mobile= (String) map.get("mobile");
            if (!StringUtil.isBlankOrNull(mobile)){
                TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
                tbExpertUserExample.createCriteria().andMobileEqualTo(mobile);
                List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
                if(tbExpertUserList.size()>0){
                    TbExpertUser tbExpertUser=tbExpertUserList.get(0);
                    String exp=(String) map.get("expert");
                    if (!StringUtil.isBlankOrNull(exp)){
                        int expert= Integer.parseInt(exp);
                        tbExpertUser.setExpert((byte) expert);
                    }
                    int signStatu= Integer.parseInt((String) map.get("signStatu"));
                    tbExpertUser.setSignStatu((byte) signStatu);
                    String interViewDesc= (String) map.get("interViewDesc");
                    tbExpertUser.setIntervierDesc(interViewDesc);
                    tbExpertUserMapper.updateByExampleSelective(tbExpertUser,tbExpertUserExample);
                    return APIResponse.returnSuccess("面试录入成功");
                }
                return APIResponse.returnFail(130,"该达人不存在");
            }else{
                return APIResponse.returnFail(120,"达人手机号不存在");
            }
        }
        return APIResponse.returnFail(110,"参数不能为空，请重试");
    }

    /**
     * 分页查询所以推荐人信息及条件搜索
     * @param reqSerchReferUser
     * @return
     */
    @Override
    public APIResponse<PageObj<List<TbReferUser>>> getReferUserMsg(ReqSerchReferUser reqSerchReferUser) {
        Map<String,Object> paramMap=reqSerchReferUser.getParamMap();
        TbReferUserExample tbReferUserExample=new TbReferUserExample();
        getReferMsg(paramMap,tbReferUserExample);
        int count=tbReferUserMapper.countByExample(tbReferUserExample);
        tbReferUserExample.setOrderByClause("id desc");
        Page page=new Page(reqSerchReferUser.getPageNum(),reqSerchReferUser.getPageSize(),count);
        tbReferUserExample.setPage(page);
        List<TbReferUser> tbReferUserList=tbReferUserMapper.selectByExample(tbReferUserExample);
        PageObj<List<TbReferUser>> result=PageObj.create(count,reqSerchReferUser.getPageNum(),reqSerchReferUser.getPageSize(),tbReferUserList);
        return APIResponse.returnSuccess(result);
    }

    /**
     * 分页查询所有推荐人信息及条件搜索，结果导出
     * @param reqSerchReferUser
     * @return
     */
    @Override
    public APIResponse<List<TbReferUser>> exportReferUserMsg(ReqSerchReferUser reqSerchReferUser) {
        Map<String,Object> paramMap=reqSerchReferUser.getParamMap();
        TbReferUserExample tbReferUserExample=new TbReferUserExample();
        getReferMsg(paramMap,tbReferUserExample);
        List<TbReferUser> tbReferUserList=tbReferUserMapper.selectByExample(tbReferUserExample);
        return APIResponse.returnSuccess(tbReferUserList);

    }

    private void getReferMsg(Map<String,Object> paramMap,TbReferUserExample tbReferUserExample) {
        if (paramMap!=null){
            String beginTime= (String) paramMap.get("beginTime");
            String endTime= (String) paramMap.get("endTime");
            TbReferUserExample.Criteria criteria=tbReferUserExample.createCriteria();
            if(!StringUtil.isBlankOrNull(beginTime) && !StringUtil.isBlankOrNull(endTime)){
                    beginTime=beginTime+" 00:00:00";
                    endTime=endTime+" 23:59:59";
                criteria.andSignTimeBetween(DateUtils.strToDate(beginTime,DateUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS),DateUtils.strToDate(endTime,DateUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS));
            }
            String mobile= (String) paramMap.get("mobile");
            if(!StringUtil.isBlankOrNull(mobile)){
                criteria.andMobileEqualTo(mobile);
            }
            Object ostart=paramMap.get("startMoney");
            Object oend= paramMap.get("endMoney");
            if(ostart!=null &&!"".equals(ostart) && oend!=null && !"".equals(oend)){
                int startMoney= Integer.parseInt((String) ostart);
                int endMoney= Integer.parseInt((String) oend);
                if (startMoney==endMoney){//0没有拿到奖励
                    criteria.andAllMoneyEqualTo(startMoney);
                }else if (endMoney==-1) {//>5000奖励
                    criteria.andAllMoneyGreaterThan(startMoney);
                }else if(startMoney<endMoney){
                    criteria.andAllMoneyNotBetween(0,startMoney);
                }
            }
        }
    }

    /**
     * 确定推荐人已提现
     * @param mobile
     * @return
     */
    @Override
    public APIResponse confirmReferMoney(String mobile) {
        if(StringUtil.isBlankOrNull(mobile)){
            return APIResponse.returnFail("手机号不能为空");
        }
        TbReferUserExample tbReferUserExample=new TbReferUserExample();
        tbReferUserExample.createCriteria().andMobileEqualTo(mobile);
        List<TbReferUser> tbReferUserList=tbReferUserMapper.selectByExample(tbReferUserExample);
        if (tbReferUserList.size()>0){
            TbReferUser tbReferUser=tbReferUserList.get(0);
            tbReferUser.setStatus((byte) 1);
            tbReferUserMapper.updateByExampleSelective(tbReferUser,tbReferUserExample);
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("该用户不存在");
    }

    /**
     *分页查询推荐人推荐所有达人信息
     * @param reqSerchReferUser
     * @return
     */
    @Override
    public APIResponse<RespMyReferUser> getMyExpertUserMsg(ReqSerchReferUser reqSerchReferUser) {
        if (reqSerchReferUser==null || reqSerchReferUser.getParamMap()==null){
            return APIResponse.returnFail("推荐人电话不能为空");
        }
        Map<String,Object> paramMap=reqSerchReferUser.getParamMap();
        String mobile= (String) paramMap.get("mobile");
        if (StringUtil.isBlankOrNull(mobile)){
            return APIResponse.returnFail("推荐人电话不能为空");
        }
        TbReferUserExample tbReferUserExample=new TbReferUserExample();
        tbReferUserExample.createCriteria().andMobileEqualTo(mobile);
        //查询推荐人信息
        List<TbReferUser> tbReferUserList=tbReferUserMapper.selectByExample(tbReferUserExample);
        RespMyReferUser respMyReferUser=new RespMyReferUser();
        if (tbReferUserList.size()>0){
            TbReferUser tbReferUser=tbReferUserList.get(0);
            respMyReferUser.setReferNum(tbReferUser.getAllNum());
            respMyReferUser.setPrettyNum(tbReferUser.getPrettyNum());
            respMyReferUser.setExpertNum(tbReferUser.getExpertNum());
            //查询推荐人推荐人的人数信息
            TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
            tbExpertUserExample.createCriteria().andRefermobileEqualTo(mobile);
            List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
            if (tbExpertUserList.size()>0){//推荐人推荐了达人
                paramMap.put("pageNum",reqSerchReferUser.getPageNum());
                paramMap.put("pageSize",reqSerchReferUser.getPageSize());
                List<RespSearchExpert> respSearchExpertList=myDefineMapper.getExpertReferUser(paramMap);
                int count=myDefineMapper.coutExpertReferUser(paramMap);
                PageObj<List<RespSearchExpert>> result=PageObj.create(count,reqSerchReferUser.getPageNum(),reqSerchReferUser.getPageSize(),respSearchExpertList);
                respMyReferUser.setRespSearchExpertList(result);
                return APIResponse.returnSuccess(respMyReferUser);
            }
            return APIResponse.returnFail("没有推荐达人");
        }
        return APIResponse.returnFail("查询用户不存在");
    }

    /**
     * 达人编辑页面
     * @param id
     * @return
     */
    @Override
    public APIResponse<TbExpertUser> editExpertInfo(Integer id) {
        if(null ==id){
            return APIResponse.returnFail("达人编号不能为空");
        }
        TbExpertUser tbExpertUser=tbExpertUserMapper.selectByPrimaryKey(id);
        return APIResponse.returnSuccess(tbExpertUser);
    }

    /**
     * 跟新达人信息
     * @param id
     * @param name
     * @param url
     * @return
     */
    @Override
    public APIResponse updateExpertInfo(Integer id,String name,String url) {
        if(null ==id){
            return APIResponse.returnFail("达人编号不能为空");
        }
        TbExpertUser tbExpertUser=tbExpertUserMapper.selectByPrimaryKey(id);
        tbExpertUser.setName(name);
        tbExpertUser.setPhotoUrl(url);
        tbExpertUserMapper.updateByPrimaryKey(tbExpertUser);
        return APIResponse.returnSuccess("跟新成功");
    }

}
